<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use App\Comment\Comment;
use DB;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request   
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        // 如果不是管理员或者没有登录;则重定向到登录页面
        if (!Auth::check() && !$request->session()->has('adminInfo') ) {
            return redirect('admin/login/index');
        }

        
        $mcaUrl = $this->getPermission($request);
        $comment = new Comment();
        $adminInfo = session('adminInfo');
        $result = $comment->check($mcaUrl, $adminInfo['id']);
        // dd($result);
        if(!$result) {
            return redirect('error')->with('error','权限不足！');
            // echo '权限不足！';exit;
        }
        
        return $next($request);
    }


    // 获取当前路由需要的权限
    public  function getPermission($request)
    {
        $actions = $request->route()->getAction();
        // dd($actions);
        if (empty($actions['auth'])) {
            echo "路由没有设置权限";exit;
        }
        return $actions['auth'];
    }
}
